package com.solution.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.solution.model.Communication;

public class SMSSender {
	private static final Logger log = Logger.getLogger(SMSSender.class);
	private static String smsURL;
	private static String userName;
	private static String password;
	private static String sid;
	static{
		try{
			smsURL = Repository.getRepository().getSystemProperty("smsURL");
			userName = Repository.getRepository().getSystemProperty("username");
			password = Repository.getRepository().getSystemProperty("password");
			sid = Repository.getRepository().getSystemProperty("sid");
		} 
		catch (Exception e) {
			log.error("SMS sender construction error", e);
			throw new RuntimeException(e);
		}
	}
	
	public static void sendDynamicContentSMS(List<String> mobileNumbers, Map<String, String> variableStrings, String templateName, long ownerId, short ownerType){
		try{
			String strMessage = MessageCreation.getMessage(variableStrings, templateName);
			//external IP
			//URL url = new URL("http://221.134.14.47:8080/SMSSender/sendSMS?number="+get91AppendedMobileNumber(mobileNumbers.get(0))+"&message="+URLEncoder.encode(strMessage));
			URL url = new URL("http://192.168.100.131:8080/SMSSender/sendSMS?number="+get91AppendedMobileNumber(mobileNumbers.get(0))+"&message="+URLEncoder.encode(strMessage));
//			String urlString = smsURL+"?usr="+userName+"&pass="+password+"&msisdn=";
//			urlString = urlString+get91AppendedMobileNumber(mobileNumbers.get(0));
//			for(int i=1;i<mobileNumbers.size();i++){
//				urlString = urlString+","+get91AppendedMobileNumber(mobileNumbers.get(i));
//			}
//			URL url = new URL(urlString+"&sid="+URLEncoder.encode(sid)+"&msg="+URLEncoder.encode(strMessage)+"&mt=0");
			new SMSProcessorThread(url).start();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public static boolean sendStaticContentSMS(Communication communication){
		boolean result = false;
		try{
			//external IP
			//URL url = new URL("http://221.134.14.47:8080/SMSSender/sendSMS?number="+get91AppendedMobileNumber(communication.getMobileNumber())+"&message="+URLEncoder.encode(communication.getContent()));
			URL url = new URL("http://192.168.100.131:8080/SMSSender/sendSMS?number="+get91AppendedMobileNumber(communication.getMobileNumber())+"&message="+URLEncoder.encode(communication.getContent()));
//			URL url = new URL(smsURL+"?usr="+userName+"&pass="+password+"&msisdn="+get91AppendedMobileNumber(communication.getMobileNumber())+"&sid="+URLEncoder.encode(sid)+"&msg="+URLEncoder.encode(communication.getContent())+"&mt=0");
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			conn.connect();
			log.info("The response code is :"+conn.getResponseCode());
			if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				log.info("Response is Good");
				BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			    String responceString;
			    log.info("RESPONSE STARTS:");
			    while ((responceString=in.readLine()) != null){
			    	log.info("Response is : "+responceString);
			    	if(responceString.trim().contains(" ")){
			    		return false;
			    	}
			    }
			    in.close();
			    result = true;
			}
			else{
				log.info("Could not connect to host....");
				result = false;
			}
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return result;
	}
	
	private static class  SMSProcessorThread extends Thread{
        private URL url;
        SMSProcessorThread(URL urlValue){
        	url = urlValue;
        }
        public void run(){
            try {
            	HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    			conn.connect();
    			log.info("The response code is :"+conn.getResponseCode());
    			if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
    				log.info("Response is Good");
    				BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    			    String responceString;
    			    log.info("RESPONSE STARTS:");
    			    while ((responceString=in.readLine()) != null){
    			    	log.info("Response is : "+responceString);
    			    }
    			    in.close();
    			}
    			else{
    				log.info("Could not connect to host....");
    			}
            } catch (Exception e) {
                log.error("SMS sending error", e);
            }
        }
	}
	
	private static String get91AppendedMobileNumber(String mobileNumber){
		return "91"+mobileNumber.substring(mobileNumber.length()-10);
		//return mobileNumber.substring(mobileNumber.length()-10);
	}
}
